package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.filter.UserThreadLocal;
import com.drd.dt.modular.dao.ShareActivityMapper;
import com.drd.dt.modular.dto.ShareActivityDTO;
import com.drd.dt.modular.entity.ShareActivity;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.ShareActivityService;
import com.drd.dt.util.EmojiUtil;
import com.drd.dt.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
@Transactional
public class ShareActivityServiceImpl extends ServiceImpl<ShareActivityMapper, ShareActivity> implements ShareActivityService {
    private final static Logger logger = LoggerFactory.getLogger(ShareActivityServiceImpl.class);

    @Autowired
    private ShareActivityMapper shareActivityMapper;

    /**
     * 用户点击拆红包（首页点红包进入）
     **/
    @Override
    public Tip clickRedPacket(Integer user_id, String token_id) throws Exception{
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        JSONObject activity_info = new JSONObject();
        //获取当前用户最后一个分享拆红包活动
        ShareActivity activity = shareActivityMapper.getMyRedPacketInfo(user_id);
        Date now = new Date();
        if (null != activity){
            Integer status = activity.getStatus();//活动状态（1进行中  2已失效  3已完成）
            if (!StringUtils.isEmpty(status) && (status == 1 || status == 3)) {//进行中或已完成时
                String start_time = activity.getStart_time();
                String expire_time = activity.getExpire_time();
                Integer id = activity.getId();
                if (!StringUtils.isEmpty(start_time) && !StringUtils.isEmpty(expire_time)){
                    SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
                    Date start = y_m_d_h_m_s.parse(start_time);
                    Date expire = y_m_d_h_m_s.parse(expire_time);
                    if (start.getTime() < now.getTime() && expire.getTime() > now.getTime()){//当活动时间在有效期内时
                        activity_info = getTaskStage(activity);//获取任务阶段信息
                    }else {//更新活动状态为已失效
                        ShareActivity updateActivity = new ShareActivity();
                        updateActivity.setId(id);
                        updateActivity.setStatus(2);
                        shareActivityMapper.updateById(updateActivity);
                        activity_info.put("stage","0-0");
                        activity_info.put("list",new JSONArray());
                        activity_info.put("info",activity);
                        activity_info.put("status","3");//失效
                    }
                }
            }else {
                activity_info = insertShareActivity(activity_info, user_id, now);
            }
        }else {//还没有活动时
            activity_info = insertShareActivity(activity_info, user_id, now);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),activity_info);
    }

    /**
     * 用户拆红包、分享好友和群
     **/
    @Override
    public Tip shareGroup(Integer user_id, String token_id,Integer type) {
        logger.info("【用户："+user_id+"开始分享群，调用shareGroup()方法接口...】");
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        //type 类型（1开启红包 2分享好友  3分享群）
        JSONObject result = new JSONObject();
        String money = "0";
        ShareActivity activity = shareActivityMapper.getMyRedPacketInfo(user_id);
        if (null != activity){
            Double t_money = Double.valueOf(activity.getTotal_money());
            Double random_money = Double.valueOf(activity.getRandom_money());
            Double group_first = Double.valueOf(activity.getGroup_first_click());
            Double group_second = Double.valueOf(activity.getGroup_second_click());
            ShareActivity updateActivity = new ShareActivity();
            updateActivity.setId(activity.getId());
            if (type == 1 && t_money == 0){
                logger.info("【用户："+user_id+"开始拆红包...】");
                //生成6.66到8.88之间的随机金额
                t_money = 6.66 + ((8.88 - 6.66) * new Random().nextDouble());
                money = String.format("%.2f",t_money);
                updateActivity.setTotal_money(money);
                shareActivityMapper.updateById(updateActivity);//更新分享群获得的金额
            }else if (type == 2 && random_money == 0){
                logger.info("【用户："+user_id+"开始分享好友...】");
                //第一次拆获取总金额65%到85%的随机金额
                Double r_money = t_money*0.65 + ((t_money*0.85 - t_money*0.65) * new Random().nextDouble());
                DecimalFormat df = new DecimalFormat("######0.00");
                updateActivity.setRandom_money(Double.valueOf(df.format(r_money)));
                shareActivityMapper.updateById(updateActivity);//更新分享群获得的金额
            }else if (type == 3 && group_first == 0 && group_second == 0){
                logger.info("【用户："+user_id+"开始第一次分享群...】");
                money = getRandomMoney(activity);
                updateActivity.setGroup_first_click(money);
                shareActivityMapper.updateById(updateActivity);//更新分享群获得的金额
            }else if (type == 3 && group_first > 0 && group_second == 0){
                logger.info("【用户："+user_id+"开始第二次分享群...】");
                money = getRandomMoney(activity);
                updateActivity.setGroup_second_click(money);
                shareActivityMapper.updateById(updateActivity);//更新分享群获得的金额
            }else {
                return ResultUtil.result(BizExceptionEnum.SHARE_GROUP_IS_FINISH.getCode(), BizExceptionEnum.SHARE_GROUP_IS_FINISH.getMessage());
            }
        }
        result.put("money",money);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),result);
    }

    /**
     * 新增分享活动
     */
    private JSONObject insertShareActivity(JSONObject activity_info,Integer user_id,Date now){
        ShareActivity insertActivity = new ShareActivity();
        //获取1天后时间(红包过期时间)
        SimpleDateFormat sdf = Constant.y_M_d_H_m_s;
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        String expire_time = sdf.format(cal.getTime());

        insertActivity.setUser_id(user_id);
        insertActivity.setStatus(1);
        insertActivity.setCreate_time(sdf.format(now));
        insertActivity.setStart_time(sdf.format(now));
        insertActivity.setExpire_time(expire_time);
        shareActivityMapper.insert(insertActivity);
        activity_info.put("stage","1-0");
        activity_info.put("list",new JSONArray());
        activity_info.put("info",insertActivity);
        activity_info.put("status","1");//第一次开启红包
        return activity_info;
    }

    /**
     * 获取当前任务到达哪个阶段
     */
    private JSONObject getTaskStage(ShareActivity activity){
        String stage = "1-0";
        JSONObject result = new JSONObject();
        result.put("status","2");//进行中
        JSONArray info = new JSONArray();
        if (null != activity){
            Integer user_id = activity.getUser_id();
            String start_time = activity.getStart_time();
            String expire_time = activity.getExpire_time();
            List<User> users = shareActivityMapper.getInvitePeople(user_id,start_time,expire_time);//获取活动期间邀请的人
            if (users.size() == 0){//没有邀请人时
                Double total_money = Double.valueOf(activity.getTotal_money());
                Double group_first_click = Double.valueOf(activity.getGroup_first_click());
                Double random_money = Double.valueOf(activity.getRandom_money());
                Double group_second_click = Double.valueOf(activity.getGroup_second_click());

                if (total_money == 0){//还未点击领取红包时
                    result.put("status","1");//第一次开启红包
                }
                if (random_money == 0){//未分享好友
                    stage = "1-0";
                }else if (group_first_click > 0 && group_second_click > 0){//分享二次群
                    stage = "2-2";
                }else if (group_first_click > 0 && group_second_click == 0){//分享一次群
                    stage = "2-1";
                }else {//未分享群
                    stage = "2-0";
                }
            }else {
                Double first = Double.valueOf(activity.getInvite_first_people());
                Double second = Double.valueOf(activity.getInvite_second_people());
                if (users.size() == 1){//已邀请了一个人
                    if (first == 0){
                        ShareActivity updateActivity = new ShareActivity();
                        String randomMoney = getRandomMoney(activity);
                        updateActivity.setId(activity.getId());
                        updateActivity.setInvite_first_people(randomMoney);//设置第一次邀请人金额
                        activity.setInvite_first_people(randomMoney);
                        shareActivityMapper.updateById(updateActivity);
                    }
                    stage = "3-1";
                }else if (users.size() == 2){//已邀请了二个人
                    if (second == 0){
                        ShareActivity updateActivity = new ShareActivity();
                        String first_randomMoney ;
                        if (first == 0){//当邀请了第一个人还未更新金额时
                            first_randomMoney = getRandomMoney(activity);
                            updateActivity.setInvite_first_people(first_randomMoney);
                            activity.setInvite_first_people(first_randomMoney);
                        }
                        String randomMoney = getRandomMoney(activity);
                        updateActivity.setId(activity.getId());
                        updateActivity.setInvite_second_people(randomMoney);//设置第二次邀请人金额
                        activity.setInvite_second_people(randomMoney);
                        shareActivityMapper.updateById(updateActivity);
                    }
                    stage = "3-2";
                }else if (users.size() == 3){//已邀请了三个人
                    Double third = Double.valueOf(activity.getInvite_third_people());
                    if (third == 0){
                        ShareActivity updateActivity = new ShareActivity();
                        String first_randomMoney ;
                        String second_randomMoney ;
                        if (first == 0){//当邀请了第一个人还未更新金额时
                            first_randomMoney = getRandomMoney(activity);
                            updateActivity.setInvite_first_people(first_randomMoney);
                            activity.setInvite_first_people(first_randomMoney);
                        }
                        if (second == 0){//当邀请了第二个人还未更新金额时
                            second_randomMoney = getRandomMoney(activity);
                            updateActivity.setInvite_second_people(second_randomMoney);
                            activity.setInvite_second_people(second_randomMoney);
                        }
                        String randomMoney = getRandomMoney(activity);
                        Integer id = activity.getId();
                        updateActivity.setId(id);
                        updateActivity.setInvite_third_people(randomMoney);//设置第三次邀请人金额为剩余的金额
                        activity.setInvite_third_people(randomMoney);
                        shareActivityMapper.updateById(updateActivity);
                        rebateActivityMoney(id);//返现到账户
                    }
                    stage = "3-3";
                    result.put("status","4");//已完成
                }
            }
            info = getMoneyInfo(activity, users);
        }
        result.put("stage",stage);
        result.put("list",info);
        result.put("info",activity);
        return result;
    }

    /**
     * 用户完成活动任务时返红包到账户
     */
    private void rebateActivityMoney(Integer id){
        ShareActivity activity = shareActivityMapper.selectById(id);
        Integer status = activity.getStatus();
        Integer user_id = activity.getUser_id();
        if (status == 1){//进行中 且任务已完成可提现
            Double total_money = Double.valueOf(activity.getTotal_money());//可提现额度
            Double random_money = Double.valueOf(activity.getRandom_money());//第一次点击随机金额
            Double group_first = Double.valueOf(activity.getGroup_first_click());//第一次分享群获得金额
            Double group_second = Double.valueOf(activity.getGroup_second_click());//第二次分享群获得金额
            Double invite_first = Double.valueOf(activity.getInvite_first_people());//邀请第一个人获得金额
            Double invite_second = Double.valueOf(activity.getInvite_second_people());//邀请第二个人获得金额
            Double invite_third = Double.valueOf(activity.getInvite_third_people());//邀请第三个人获得金额
            Double gain = random_money + group_first + group_second + invite_first + invite_second + invite_third;
            Double distance = total_money - gain;//差价金额
            if (distance > -0.06 && distance < 0.06){//差距在五分钱内时满足提现
                Map param = new HashMap();
                param.put("user_id",user_id);
                param.put("money",total_money);
                param.put("type","9");
                param.put("remark","活动返佣");
                param.put("action_type","1");
                shareActivityMapper.insertBalanceDetail(param);//插入balance表记录
                param.put("message_type","5");
                shareActivityMapper.insertMessageMoney(param);//插入MessageMoney消息表记录
                ShareActivityDTO share = shareActivityMapper.getUserProfitInfo(user_id);//获取用户活动金额信息
                if (null != share){//存在
                    param.put("id",share.getId());
                    shareActivityMapper.updateUserActivityBalance(param);//更新用户活动佣金
                }else {
                    shareActivityMapper.insertUserActivityBalance(param);//新增用户活动佣金
                }
                ShareActivity updateActivity = new ShareActivity();
                updateActivity.setId(id);
                updateActivity.setStatus(3);
                shareActivityMapper.updateById(updateActivity);//更新任务状态为已完成
            }
        }
    }

    /**
     * 拆开随机金额的红包
     */
    private String getRandomMoney(ShareActivity activity){
        String result = "0";
        Double second = Double.valueOf(activity.getInvite_second_people());
        Double third = Double.valueOf(activity.getInvite_third_people());
        Double money = Double.valueOf(activity.getTotal_money())-Double.valueOf(activity.getRandom_money())-Double.valueOf(activity.getGroup_first_click())-
                      Double.valueOf(activity.getGroup_second_click())-Double.valueOf(activity.getInvite_first_people())-second-third;
        if (money > 0){
            if (second > 0 && third == 0){//邀请到最后一位时，获取剩余全部未获取金额
                result = String.format("%.2f",money);
            }else {
                Double ran = 0.01 + Math.random() * (money * 0.6 - 0.01);
                result = String.format("%.2f",ran);
            }
        }
        return result;
    }

    /**
     * 返回拆红包信息
     */
    private JSONArray getMoneyInfo(ShareActivity activity,List<User> users){
        JSONArray info = new JSONArray();
        Double random_money = Double.valueOf(activity.getRandom_money());
        Double group_first = Double.valueOf(activity.getGroup_first_click());
        Double group_second = Double.valueOf(activity.getGroup_second_click());
        Double invite_first = Double.valueOf(activity.getInvite_first_people());
        Double invite_second = Double.valueOf(activity.getInvite_second_people());
        Double invite_third = Double.valueOf(activity.getInvite_third_people());
        User user = UserThreadLocal.get();
        String head_pic = user.getHead_pic();
        String nick_name = user.getNick_name();
        if (!StringUtils.isEmpty(nick_name)){
            nick_name = EmojiUtil.decode(nick_name);
        }
        if (random_money > 0){
            JSONObject r_money = new JSONObject();
            r_money.put("money",random_money);
            r_money.put("head_pic",head_pic);
            r_money.put("nick_name",nick_name);
            info.add(r_money);
            if (group_first > 0){
                JSONObject share2group1 = new JSONObject();
                share2group1.put("money",group_first);
                share2group1.put("head_pic",head_pic);
                share2group1.put("nick_name",nick_name);
                info.add(share2group1);
                if (group_second > 0){
                    JSONObject share2group2 = new JSONObject();
                    share2group2.put("money",group_second);
                    share2group2.put("head_pic",head_pic);
                    share2group2.put("nick_name",nick_name);
                    info.add(share2group2);
                    if (invite_first > 0 && users.size() > 0){
                        JSONObject invite1 = new JSONObject();
                        invite1.put("money",invite_first);
                        invite1.put("head_pic",users.get(0).getHead_pic());
                        invite1.put("nick_name",EmojiUtil.decode(users.get(0).getNick_name()));
                        info.add(invite1);
                        if (invite_second > 0 && users.size() > 1){
                            JSONObject invite2 = new JSONObject();
                            invite2.put("money",invite_second);
                            invite2.put("head_pic",users.get(1).getHead_pic());
                            invite2.put("nick_name",EmojiUtil.decode(users.get(1).getNick_name()));
                            info.add(invite2);
                            if (invite_third > 0 && users.size() > 2){
                                JSONObject invite3 = new JSONObject();
                                invite3.put("money",invite_third);
                                invite3.put("head_pic",users.get(2).getHead_pic());
                                invite3.put("nick_name",EmojiUtil.decode(users.get(2).getNick_name()));
                                info.add(invite3);
                            }
                        }
                    }
                }
            }
        }
        return info;
    }

}
